import React, { Component } from 'react'

import { SearchBar } from 'antd-mobile'

import { getCity } from '../../../utils'
import { getCommunity } from '../../../apis/city'

import styles from './index.module.css'

export default class Search extends Component {
	// 当前城市id
	cityId = getCity().value
	timer = null
	state = {
		// 搜索框的值
		searchTxt: '',
		tipsList: []
	}

	onTipsClick = item => {
		this.props.history.replace('/rent/add', { name: item.communityName, id: item.community })
	}

	// 渲染搜索结果列表
	renderTips = () => {
		const { tipsList } = this.state

		return tipsList.map(item => (
			<li key={item.community} className={styles.tip} onClick={() => { this.onTipsClick(item) }}>
				{item.communityName}
			</li>
		))
	}

	// 处理搜索框输入
	handleSearchTxt = (val) => {
		this.setState({ searchTxt: val })
		if (!val) {
			this.setState({ tipsList: [] })
			return
		}
		clearTimeout(this.timer)
		this.timer = setTimeout(async () => {
			const tipsList = await getCommunity({ name: val, id: this.cityId })
			this.setState({ tipsList })
		}, 500)
	}

	render () {
		const { history } = this.props
		const { searchTxt } = this.state

		return (
			<div className={styles.root}>
				{/* 搜索框 */}
				<SearchBar
					placeholder="请输入小区或地址"
					value={searchTxt}
					showCancelButton={true}
					onCancel={() => history.replace('/rent/add')}
					onChange={this.handleSearchTxt}
				/>

				{/* 搜索提示列表 */}
				<ul className={styles.tips}>{this.renderTips()}</ul>
			</div>
		)
	}
}
